package com.marketapp.validators;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.marketapp.domain.Sector;
import com.marketapp.helper.ServiceException;
import com.marketapp.service.ISectorService;
import com.marketapp.util.StringUtil;

@Component
public class SectorValidator implements Validator{
	
	@Autowired
	ISectorService sectorService;

	public ISectorService getSectorService() {
		return sectorService;
	}

	public void setSectorService(ISectorService sectorService) {
		this.sectorService = sectorService;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return Sector.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors error) {
		ValidationUtils.rejectIfEmpty(error, "sectorName", "sector.required");
		Sector sector = (Sector) target;
		try {
			if(sectorService.checkifSectorExist(sector.getSectorName())
					&& !StringUtil.ifBlankorNull(sector.getSectorName())){
				error.reject("sector.exist");
			}
			
		} catch (ServiceException e) {
			e.printStackTrace();
		}
	}

}
